﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Aga.GestionDeArchivos.Domain.Entities;
using System.Data.Objects;

namespace Aga.GestionDeArchivos.Storage
{
    public class RemitoRepository : RepositoryBase<Remito>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RemitoRepository"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        public RemitoRepository(AgaEntities context)
            : base(context) { }

        /// <summary>
        /// Adds to context.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected override Action<Remito> AddToContext(Remito entity)
        {
            return delegate { Context.AddToRemitos(entity); };
        }

        /// <summary>
        /// Gets the entity set.
        /// </summary>
        /// <value>The entity set.</value>
        protected override ObjectSet<Remito> EntitySet
        {
            get { return Context.Remitos; }
        }

        public override void Save(Remito entity)
        {
            if (entity.EntityState == System.Data.EntityState.Added)
            {
                int ultimoNumero = ObtenerUltimoNumero();
                entity.Numero = ultimoNumero + 1;
            }

            base.Save(entity);
        }

        private int ObtenerUltimoNumero()
        {
            try
            {
                return EntitySet.Max(r => r.Numero);
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }
}
